<?php
require_once __DIR__ . '/XML.php';
/*
 * @brief url封装类，将常用的url请求操作封装在一起
 * */
class Request {
    private $error;

    public function __construct() {
        // $this->error = new ErrorCase();
    }

    static function convertUrlQuery($query) {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }

    /**
     * combineURL
     * 拼接url
     * @param string $baseURL   基于的url
     * @param array  $keysArr   参数列表数组
     * @return string           返回拼接的url
     */
    static public function combineURL($baseURL, $keysArr, $mark = '?') {
        $combined = $baseURL . $mark;
        $valueArr = array();

        foreach ($keysArr as $key => $val) {
            $val = rawurlencode($val);
            $valueArr[] = "$key=$val";
        }

        $keyStr = implode("&", $valueArr);
        $combined .= ($keyStr);

        return $combined;
    }

    /**
     * get_contents
     * 服务器通过get请求获得内容
     * @param string $url       请求的url,拼接后的
     * @return string           请求返回的内容
     */
    static public function get_contents($url, $headers = null, $isMobile = false) {
        // if (ini_get("allow_url_fopen") == "1") {
        //     $response = file_get_contents($url);
        // }else{
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($isMobile) {
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4');
        }
        if (!is_null($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        $response =  curl_exec($ch);
        curl_close($ch);
        // }

        //-------请求为空
        // if(empty($response)){
        //     $this->error->showError("50001");
        // }

        return $response;
    }

    /**
     * get
     * get方式请求资源
     * @param string $url     基于的baseUrl
     * @param array $keysArr  参数列表数组      
     * @return string         返回的资源内容
     */
    static public function get($url, $keysArr = [], $headers = null) {
        $combined = self::combineURL($url, $keysArr);
        return self::get_contents($combined, $headers);
    }

    // 
    /**
     * get
     * get方式请求资源
     * @param string $url     基于的baseUrl
     * @param array $keysArr  参数列表数组      
     * @return string         返回的资源内容
     */
    static public function get_mobile($url, $keysArr = [], $headers = null) {
        $combined = self::combineURL($url, $keysArr);
        return self::get_contents($combined, $headers, true);
    }

    /**
     * post
     * post方式请求资源
     * @param string $url       基于的baseUrl
     * @param array $keysArr    请求的参数列表
     * @param int $flag         标志位
     * @return string           返回的资源内容
     */
    static public function post($url, $keysArr, $flag = 0) {

        $ch = curl_init();
        if (!$flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr);
        curl_setopt($ch, CURLOPT_URL, $url);
        $ret = curl_exec($ch);

        curl_close($ch);
        return $ret;
    }

    /**
     * post_json
     * post json方式请求资源
     * @param string $url       基于的baseUrl
     * @param string $jsonStr    请求的参数JSON
     * @return string           返回的资源内容
     */
    static public function post_json($url, $jsonStr) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        ));
        $response = curl_exec($ch);
        // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $response;
    }

    /**
     * post_json
     * post json方式请求资源
     * @param string $url       基于的baseUrl
     * @param string $jsonArray    请求的参数数组
     * @return string           返回的资源内容
     */
    static public function post_jsonArr($url, $arr, $getArr = null) {

        $combined = is_null($getArr) ? $url : self::combineURL($url, $getArr);
        $jsonStr = json_encode($arr, JSON_UNESCAPED_UNICODE);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $combined);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        ));
        $response = curl_exec($ch);
        // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $response;
    }

    /**
     * post_json
     * post json方式请求资源
     * @param string $url       基于的baseUrl
     * @param string $xml    请求的参数xml
     * @return string           返回的资源内容
     */
    static public function post_xml($url, $arr, $ssl = null) {
        $xmlStr = XML::arr2xml($arr);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($xmlStr)
        ));
        if (!is_null($ssl)) {
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, $ssl['certPath']);
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, $ssl['keyPath']);
        }

        $response = curl_exec($ch);
        // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $response;
    }

    /**
     * post_json上传
     * post json方式上传
     * @param string $url       基于的baseUrl
     * @param array $post_data    请求的参数数据
     * @param string $fileName    文件名
     * @return string           返回的资源内容
     */
    static public function post_upload($url, $post_data, $fileKey, $fileName) {
        $data = [
            $fileKey => new CURLFile(realpath($fileName)),
        ];

        foreach ($post_data as $key => $value) {
            $data[$key] = $value;
        }


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }
}
